// Thud - a dynamic object-oriented language
// Copyright (C) 2009,2010 David H. Hovemeyer <david.hovemeyer@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

/*
 * DataOutputStream.cpp
 *
 *  Created on: Nov 28, 2009
 *      Author: dhovemey
 */

#include <memory>
#include <netinet/in.h>
#include "util/Utf8TextCoder.h"
#include "util/DataOutputStream.h"

DataOutputStream::DataOutputStream(OutputStream *outputStreamToAdopt)
	: m_delegate(outputStreamToAdopt)
{

}

DataOutputStream::~DataOutputStream()
{
	delete m_delegate;
}

void DataOutputStream::write(int b)
{
	uint8_t buf = uint8_t(b);
	write((const void *) &buf, 1);
}

void DataOutputStream::write(const void *buf, size_t n)
{
	m_delegate->write(buf, n);
}

void DataOutputStream::writeByte(uint8_t b)
{
	write(int(b));
}

void DataOutputStream::writeShort(uint16_t s)
{
	s = htons(s);
	write((const void *) &s, sizeof(s));
}

void DataOutputStream::writeInt(uint32_t i)
{
	i = htonl(i);
	write((const void *) &i, sizeof(i));
}

void DataOutputStream::writeString(const std::wstring &s)
{
	std::auto_ptr<Utf8TextCoder> coder(new Utf8TextCoder());

	size_t len = s.size();
	if (len > 0xFFFF) {
		len = 0xFFFF;
	}

	writeShort(uint16_t(len));
	for (size_t i = 0; i < len; i++) {
		coder->encode(s[i], m_delegate);
	}
}

